import { ref } from 'vue';
import { debounce } from 'lodash-es';
import { request } from '@/service/request';
export default function useRemoteSearch(path: any) {
  const state = {
    data: ref([] as any[]),
    fetching: ref(false)
  };
  const fetchUrl = debounce(async query => {
    state.data.value = [];
    state.fetching.value = true;

    const res: any = await request.post(`${path}?param=${query}`);
    state.data.value = res.data;
    state.fetching.value = false;
  }, 800);

  const addOption = (item: any) => {
    const option = state.data.value.find(ele => {
      return ele.value === item.value;
    });
    if (!option) {
      state.data.value.push(item);
    }
  };

  return {
    fetchUrl,
    searchState: state,
    addOption
  };
}
